<template>
  <transition
    name="animate__animated animate__bounce"
    appear
    enter-active-class="animate__backInDown"
    leave-active-class="animate__zoomOut"
  >
    <li>
      <label>
        <input
          type="checkbox"
          :checked="todo.done"
          @change="handleCheck(todo.id)"
          class="cb"
        />
        <span class="sp" v-show="!todo.isEdit">{{ todo.title }}</span>
        <input
          type="text"
          :value="todo.title"
          v-show="todo.isEdit"
          @blur="handBlur(todo, $event)"
          ref="inputTitle"
        />
      </label>
      <button class="btn btn-danger" @click="deleteTodo(todo.id)">删除</button>
      <button v-show="!todo.isEdit" class="btn btn-edit" @click="Edit(todo)">
        编辑
      </button>
    </li>
  </transition>
</template>

<script>
import pubsub from "pubsub-js";
import "animate.css";
export default {
  name: "Item",
  //声明接收todo对象
  props: ["todo"],
  methods: {
    //勾选或者取消勾选
    handleCheck(id) {
      console.log(id);
      // 通知App组件对应的todo对象的done值取反
      // this.checkTodo(id);
      this.$bus.$emit("checkTodo", id);
    },
    //删除
    deleteTodo(id) {
      // if (confirm("确定删除吗")) {
      console.log(id);
      //通知App删除对应todo项
      // this.removeTodo(id);
      // this.$bus.$emit("removeTodo", id);
      pubsub.publish("removeTodo", id);
      // }
    },

    //编辑
    Edit(todo) {
      // todo.isEdit = true;
      // hasOwnProperty(propertyName)方法 是用来检测属性是否为对象的自有属性，
      // 如果是，返回true，否者false; 参数propertyName指要检测的属性名；
      if (todo.hasOwnProperty("isEdit")) {
        todo.isEdit = true;
      } else {
        this.$set(todo, "isEdit", true);
      }

      this.$nextTick(function () {
        this.$refs.inputTitle.focus();
      });
    },

    //失去焦点修改并变为文字
    handBlur(todo, e) {
      todo.isEdit = false;
      if (!e.target.value.trim()) return alert("输入不能为空");
      this.$bus.$emit("updateTodo", todo.id, e.target.value);
    },
  },
};
</script>

<style scoped>
/*item*/
li {
  list-style: none;
  height: 36px;
  line-height: 36px;
  padding: 0 5px;
  border-bottom: 1px solid #ddd;
  transition: all 0.6s;
}

li label {
  float: left;
  cursor: pointer;
}

li label li input {
  vertical-align: middle;
  margin-right: 6px;
  position: relative;
  top: -1px;
}

li button {
  float: right;
  display: none;
  margin-top: 3px;
  margin-left: 5px;
}

li:before {
  content: initial;
}

li:last-child {
  border-bottom: none;
}

li:hover {
  background-color: skyblue;
}

li:hover button {
  display: block;
}

.sp {
  margin-left: 5px;
}
</style>
